import config from '@/config'
import {
	getToken
} from '@/utils/auth'
import errorCode from '@/utils/errorCode'
import {
	toast,
	showConfirm,
	tansParams
} from '@/utils/common'
import store from "./storage.js";

let timeout = 60000 // 请求超时时间1分钟
// 是否显示重新登录
export let isRelogin = {
	show: false
};
const baseUrl = config.baseUrl

const request = config => {
	const userInfor = store.getUserInfo()
	config.header = config.header || {}
	config.header['userToken'] = getToken()
	// get请求映射params参数
	if (config.params) {
		let url = config.url + '?' + tansParams(config.params)
		url = url.slice(0, -1)
		config.url = url
	}
	return new Promise((resolve, reject) => {
		uni.request({
				method: config.method || 'get',
				timeout: config.timeout || timeout,
				url: config.baseUrl || baseUrl + config.url,
				data: {
					...config.data,
					userNumber: userInfor.number,
				},
				header: config.header,
				dataType: 'json'
			}).then(response => {
				// let [error, res] = response
				const res = response;
				// if (error) {
				// 	console.log('========================', error, response, config, baseUrl);
				// 	toast('后端接口连接异常')
				// 	reject('后端接口连接异常')
				// 	return
				// }
				const code = res.data.code || 200
				const msg = errorCode[code] || res.data.msg || res.data.message || errorCode['default']
				if (code === 400) {
					toast(msg)
					//store.clearStorage();
					return Promise.reject("无效的会话，或者会话已过期，请重新登录。");
				} else if (code === 500) {
					toast(msg)
					return Promise.reject(new Error(msg));
				} else if (code === 601) {
					toast(msg)
					return Promise.reject('error');
				} else if (code !== 200) {
					toast(msg)
					reject(code)
				}
				resolve(res.data);
			})
			.catch(error => {
				let {
					errMsg: message
				} = error
				console.log('error', error);
				console.log('message', message);
				// @ 后面拼提示类型
				const transMessage = message?.split('@');
				message = transMessage[0];
				const type = transMessage[1] || 'error';
				if (message === 'Network Error') {
					message = '后端接口连接异常'
				} else if (message?.includes('timeout')) {
					message = '系统接口请求超时'
				} else if (message?.includes('Request failed with status code')) {
					message = '系统接口' + message.substr(message.length - 3) + '异常'
				}
				toast(message)
				reject(error)
			})
	})
}

export default request